//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

package org.prx.prp.utility;

import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DatabaseAdapter {
	private static DatabaseHelper databaseHelper;
	private static SQLiteDatabase db;

	public static void initDatabaseAdapter(final Context applicationContext) {
		databaseHelper = new DatabaseHelper(applicationContext, "org.prx");
		db = databaseHelper.getWritableDatabase();
	}

	public static void closeDatabase() {

		db.close();
	}

	public static boolean createTable(final String columnNames[],
			final String tableName) {
		try {
			createTable(prepareCreateQuery(columnNames, tableName));
		} catch (Exception e) {
			//Log.d("PRPAND", "Error in create" + e.getMessage());
			return false;
		}
		return true;
	}

	private static String prepareCreateQuery(final String columnNames[],
			final String tableName) {
		final StringBuffer query = new StringBuffer();
		int index;
		query.append("CREATE TABLE IF NOT EXISTS " + tableName
				+ "(ID INTEGER,updated_at_in_utc_seconds DOUBLE,");
		for (index = 2; index < columnNames.length; index++)
			query.append(columnNames[index] + ",");
		query.append("PRIMARY KEY(id,updated_at_in_utc_seconds))");
		return query.toString();
	}

	private static String prepareWhereClause(final String columnNames[],
			final String columnValues[]) {
		final StringBuffer query = new StringBuffer();
		int index;
		query.append(columnNames[0] + "=" + columnValues[0]);
		for (index = 1; index < columnNames.length; index++)
			query.append(" AND " + columnNames[index] + "="
					+ columnValues[index]);
		return query.toString();

	}

	public static boolean insertRecord(final String tableName,
			final HashMap<String, String> columnValues,
			final String[] columnNames) {
		final ContentValues params = new ContentValues();
		for (int index = 0; index < columnNames.length; index++) {
			params.put(columnNames[index], columnValues.get(columnNames[index]));
		}
		try {
			return insertRecord(tableName, params);
		} catch (SQLiteConstraintException ex) {
			return false;
		}

	}

	public static boolean deleteRecord(final String tableName,
			final String columnNames[], final String columnValues[]) {
		return db.delete(tableName, prepareWhereClause(columnNames,
				columnValues), null) > 0;
	}

	public static boolean updateRecords(final String tableName,
			final String toBeUpdatedColumnsNames[],
			final String toBeUpdatedColumnValues[],
			final String conditionColumnsNames[],
			final String conditionColumnValues[]) {
		final ContentValues params = new ContentValues();
		for (int index = 0; index < toBeUpdatedColumnsNames.length; index++) {
			params.put(toBeUpdatedColumnsNames[index],
					toBeUpdatedColumnValues[index]);
		}
		return db.update(tableName, params, prepareWhereClause(
				conditionColumnsNames, conditionColumnValues), null) > 0;
	}

	public static Cursor executeQuery(String sqlQuery, String[] selectionArgs) {
		try {

			return db.rawQuery(sqlQuery, selectionArgs);
		} catch (Exception e) {
			Log.d("PRPAND-FromDataBaseAdapter#executeQuery", e.getMessage());
		}
		return null;
	}

	public static void createTable(String query) throws Exception {
		db.execSQL(query);

	}

	public static void deleteAllRows(String tableName) {
		db.delete(tableName, null, null);
	}

	public static boolean insertRecord(String tableName, ContentValues params) {
		try {
			return db.replaceOrThrow(tableName, null, params) > 0;
		} catch (Exception e) {
			Log.d("PRPAND-TableName", tableName);
			Log.d("PRPAND-Stuff",  params.toString());
			Log.d("PRPAND-FromDatabaseAdapter#insertRecord", e.getMessage());
		}
		return false;
	}
}
